package com.zxh.listdemo.adapter.list.common;

import android.support.annotation.IntRange;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangxuehui on 2018/2/27.
 */
public abstract class BaseListAdapter<T> extends BaseAdapter {

    protected List<T> mList;
    private int mLayoutId;

    public BaseListAdapter(@Nullable List<T> list, @LayoutRes int layoutId) {
        this.mList = list;
        this.mLayoutId = layoutId;
    }

    public BaseListAdapter(@Nullable List<T> mList) {
        this.mList = mList;
    }

    public BaseListAdapter(@LayoutRes int mLayoutId) {
        this.mLayoutId = mLayoutId;
    }


    @Override
    public int getCount() {
        return mList.size();
    }


    /**
     * 获取某一项的数据
     *
     * @param position
     * @return
     */
    @Override
    public T getItem(@IntRange int position) {
        if (position >= 0 && position < mList.size())
            return mList.get(position);
        else
            return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BaseViewHolder holder = BaseViewHolder.getViewHolder(convertView, parent, mLayoutId);
        convert(holder, position);
        return holder.getConvertView();
    }

    public abstract void convert(BaseViewHolder holder,int position);

    public void setData(@Nullable List<T> data) {
        mList.addAll(data);
        notifyDataSetChanged();
    }

    /**
     * 获取全部数据
     *
     * @return 列表数据
     */
    @NonNull
    public List<T> getData() {
        return mList;
    }

    /**
     * 对数据判null，防止null异常
     *
     * @param size Need compatible data size
     */
    private void compatibilityDataSizeChanged(int size) {
        final int dataSize = mList == null ? 0 : mList.size();
        if (dataSize == size) {
            notifyDataSetChanged();
        }
    }
}
